package com.hefan.api.controller.user;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.aliyun.opensearch.CloudsearchSearch;
import com.cat.common.entity.Page;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.util.CollectionUtils;
import com.google.common.collect.Maps;
import com.hefan.api.bean.SearchResult;
import com.hefan.api.bean.SearchResultVo;
import com.hefan.api.util.DynamicProperties;
import com.hefan.api.util.OpenSearchUtil;
import com.hefan.common.util.HttpUtils;
import com.hefan.common.util.MapUtils;
import com.hefan.user.itf.WatchCacheService;
import com.hefan.user.itf.WatchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by hbchen on 2016/10/19.
 */
@Controller
@RequestMapping("/v1/discovery")
public class SearchController {

    @Reference
    WatchService watchService;
    @Reference
    WatchCacheService watchCacheService;


    Logger logger = LoggerFactory.getLogger(SearchController.class);

    @RequestMapping("/searchAnchors")
    @ResponseBody
    public String searchAnchorsByOpensearch(HttpServletRequest request) {

        ResultBean res= new ResultBean();
        Page page = new Page();
        String result = "";
        try {
            //接参
            Map paramMap = HttpUtils.initParam(request, Map.class);
            String userId = MapUtils.getStrValue(paramMap,"userId","");
            String searchVal = MapUtils.getStrValue(paramMap,"searchVal","");
            page.pageNo = MapUtils.getIntValue(paramMap,"pageNo",page.pageNo);
            page.pageSize = MapUtils.getIntValue(paramMap,"pageSize",page.pageSize);

            if (StringUtils.isBlank(userId)){
                res.setCode(ResultCode.ParamException.get_code());
                res.setData(Maps.newHashMap());
                res.setMsg("userId有误");
                return  JSON.toJSONString(res);
            }
            // 搜索环境
            String searchIndex = DynamicProperties.getApplicationString("searchIndex");
            if(StringUtils.isBlank(searchIndex)){
                searchIndex="hefansearch";
            }
            CloudsearchSearch search = new CloudsearchSearch(OpenSearchUtil.getInstance());
            // 添加指定搜索的应用：
            search.addIndex(searchIndex);
            // 指定搜索的关键词，这里要指定在哪个索引上搜索，如果不指定的话默认在使用“default”索引（索引字段名称是您在您的数据结构中的“索引到”字段。）
            /*search.setQueryString("nick_name:"+searchVal);*/
            /*search.setQueryString("default:'词典'");*/
            if (!StringUtils.isBlank(searchVal)) {
                search.setQueryString("default:'" + searchVal + "' OR user_id:\""+ searchVal+"\"");
            }
            //分页查询
            search.setStartHit(page.getOffset() > 0 ? page.getOffset() : 0);
            //每页显示10条
            search.setHits(page.pageSize);
            // 指定搜索返回的格式。
            search.setFormat("json");
            // 设定过滤条件
            /*search.addFilter("price>10");
            // 设定排序方式 + 表示正序 - 表示降序
            search.addSort("price", "+");*/
            // 返回搜索结果
            result = search.search();

            Map map = JSON.parseObject(result, Map.class);

            if (map!=null && map.containsKey("status") && map.get("status").equals("OK")){
                SearchResult searchResult = JSON.parseObject(map.get("result").toString(),SearchResult.class);
                SearchResultVo searchResultVo = null;
                List<SearchResultVo> searchResultVoList = new ArrayList<SearchResultVo>();
                if (!CollectionUtils.isEmptyList(searchResult.getItems())) {
                    int relation;
                    for (Map rmap : searchResult.getItems()) {
                        searchResultVo = new SearchResultVo();
                        searchResultVo.setId(String.valueOf(rmap.get("user_id")));
                        searchResultVo.setName(String.valueOf(rmap.get("nick_name")));
                        searchResultVo.setHeadImg(String.valueOf(rmap.get("head_img")));
                        searchResultVo.setType(Integer.valueOf(String.valueOf(rmap.get("user_type"))));
                        searchResultVo.setWatchedCount(watchService.findWatchedCount(searchResultVo.getId()));
                        searchResultVo.setFansCount(watchService.findFansCount(searchResultVo.getId()));
                        //新关注关系0关注1互粉2未关注
                        relation = watchCacheService.getWatchRelationByUserId(userId, String.valueOf(rmap.get("user_id")));
                        searchResultVo.setIsWatched(relation);
                        searchResultVoList.add(searchResultVo);
                    }
                    res.setCode(ResultCode.SUCCESS.get_code());
                    Map resultMap = buildMap(searchResultVoList,page,searchResult.getTotal());
                    res.setData(resultMap);
                    res.setMsg(ResultCode.SUCCESS.getMsg());
                }else{
                    res.setCode(ResultCode.SUCCESS.get_code());
                    Map resultMap = buildMap(new ArrayList<>(),page,"0");
                    res.setData(resultMap);
                    res.setMsg("无记录");
                    return  JSON.toJSONString(res);
                }
            }else if(map!=null && map.containsKey("status") && map.get("status").equals("FAIL")){
                logger.error(map.get("errors").toString());
                res.setCode(ResultCode.UNSUCCESS.get_code());
                Map resultMap = buildMap(new ArrayList<>(),page,"0");
                res.setData(resultMap);
                res.setMsg("查询失败");
                return  JSON.toJSONString(res);
            }else{
                res.setCode(ResultCode.SUCCESS.get_code());
                Map resultMap = buildMap(new ArrayList<>(),page,"0");
                res.setData(resultMap);
                res.setMsg("无记录");
                return  JSON.toJSONString(res);
            }



        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            res.setCode(ResultCode.SUCCESS.get_code());
            Map resultMap = buildMap(new ArrayList<>(),page,"0");
            res.setData(resultMap);
            res.setMsg("无记录");
        }

        return JSON.toJSONString(res, SerializerFeature.DisableCircularReferenceDetect);

    }



    public long getTotalPages(long totalItems,int pageSize) {
        if (totalItems < 0) {
            return -1;
        }

        long count = totalItems / pageSize;
        if (totalItems % pageSize > 0) {
            count++;
        }
        return count;
    }

    public Map buildMap(List<SearchResultVo> searchResultVoList,Page page,String total){
        Map resultMap = Maps.newHashMap();
        resultMap.put("anchorList",searchResultVoList);
        resultMap.put("total",total);
        resultMap.put("pageNo",page.pageNo);
        resultMap.put("pageSize",page.pageSize);
        resultMap.put("totolPage",getTotalPages(Long.valueOf(total),page.pageSize));
        return resultMap;

    }

}
